<template>
  <section class="section">
    <div class="section-header">
      <h2>Mock规则管理</h2>
      <div class="section-actions">
        <el-button type="primary" @click="showMockModal">新增规则</el-button>
        <el-button @click="importMock">导入</el-button>
        <el-button @click="exportMock">导出</el-button>
      </div>
    </div>
    
    <div class="section-content">
      <div class="filter-bar">
        <el-input 
          v-model="mockFilter" 
          placeholder="搜索URL或描述" 
          style="width: 200px; margin-right: 10px;"
          clearable
        />
        <el-select 
          v-model="mockStatusFilter" 
          placeholder="状态筛选" 
          style="width: 120px;"
          clearable
        >
          <el-option label="已启用" value="enabled" />
          <el-option label="已禁用" value="disabled" />
        </el-select>
      </div>
      
      <div class="mock-list-container">
        <div v-if="filteredMockList.length === 0" class="empty-state">
          <p>暂无Mock规则</p>
        </div>
        <div 
          v-for="(mock, index) in filteredMockList" 
          :key="index" 
          class="mock-item"
        >
          <div class="mock-info">
            <div class="mock-url">{{ mock.url }}</div>
            <div class="mock-method">{{ mock.method || 'ALL' }}</div>
            <div class="mock-description">{{ mock.description }}</div>
          </div>
          <div class="mock-actions">
            <el-switch 
              v-model="mock.enabled" 
              @change="toggleMock(index)"
            />
            <el-button size="small" @click="editMock(index)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteMock(index)">删除</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Mock规则编辑弹窗 -->
    <el-dialog 
      :title="mockModalTitle" 
      :visible.sync="mockModalVisible" 
      width="600px"
    >
      <el-form :model="currentMock" label-width="100px">
        <el-form-item label="URL匹配">
          <el-input v-model="currentMock.url" placeholder="支持通配符，如 */api/*" />
        </el-form-item>
        <el-form-item label="请求方法">
          <el-select v-model="currentMock.method" placeholder="选择请求方法">
            <el-option label="ALL" value="" />
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
            <el-option label="PATCH" value="PATCH" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态码">
          <el-input-number v-model="currentMock.status" :min="100" :max="599" />
        </el-form-item>
        <el-form-item label="延迟(ms)">
          <el-input-number v-model="currentMock.delay" :min="0" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="currentMock.description" placeholder="规则描述" />
        </el-form-item>
        <el-form-item label="响应头">
          <el-input 
            v-model="currentMock.headers" 
            type="textarea" 
            :rows="3" 
            placeholder="JSON格式"
          />
        </el-form-item>
        <el-form-item label="响应内容">
          <el-input 
            v-model="currentMock.response" 
            type="textarea" 
            :rows="8" 
            placeholder="JSON格式的响应内容"
          />
          <div class="json-tools">
            <el-button size="small" @click="formatJson">格式化</el-button>
            <el-button size="small" @click="validateJson">验证</el-button>
          </div>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="currentMock.enabled" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeMockModal">取消</el-button>
        <el-button type="primary" @click="saveMock">保存</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { getStorage, setStorage } from '../../../utils/chrome'

export default {
  name: 'MockPage',
  data() {
    return {
      mockList: [],
      mockFilter: '',
      mockStatusFilter: '',
      mockModalVisible: false,
      mockModalTitle: '新增Mock规则',
      currentMock: {
        url: '',
        method: '',
        status: 200,
        delay: 0,
        description: '',
        headers: '',
        json: '',
        enabled: true
      },
      editingMockIndex: -1
    }
  },
  computed: {
    filteredMockList() {
      let filtered = this.mockList
      return filtered
    }
  },
  async mounted() {
    await this.loadMockList()
  },
  methods: {
    async loadMockList() {
      try {
        const saved = await getStorage('mockList')
        if (saved && saved['mockList']) {
          this.mockList = saved['mockList']
          console.log("🚀 ~ loadMockList ~    this.mockList :",    this.mockList )
        }
      } catch (error) {
        console.error('加载Mock规则失败:', error)
      }
    },
    
    showMockModal() {
      this.mockModalTitle = '新增Mock规则'
      this.editingMockIndex = -1
      this.currentMock = {
        url: '',
        method: '',
        status: 200,
        delay: 0,
        description: '',
        headers: '',
        json: '',
        enabled: true
      }
      this.mockModalVisible = true
    },
    
    editMock(index) {
      this.mockModalTitle = '编辑Mock规则'
      this.editingMockIndex = index
      this.currentMock = { ...this.mockList[index] }
      console.log("🚀 ~ editMock ~     this.currentMock:",     this.currentMock)
      this.mockModalVisible = true
    },
    
    deleteMock(index) {
      this.$confirm('确定要删除这个Mock规则吗？', '确认', {
        type: 'warning'
      }).then(() => {
        this.mockList.splice(index, 1)
        this.saveMockList()
        this.$message.success('Mock规则删除成功')
      })
    },
    
    toggleMock(index) {
      this.saveMockList()
      this.$message.success('Mock规则状态更新成功')
    },
    
    saveMock() {
      if (!this.currentMock.url) {
        this.$message.error('请输入URL匹配规则')
        return
      }
      
      if (this.editingMockIndex >= 0) {
        this.mockList.splice(this.editingMockIndex, 1, { ...this.currentMock })
      } else {
        this.mockList.push({ ...this.currentMock })
      }
      
      this.saveMockList()
      this.closeMockModal()
      this.$message.success('Mock规则保存成功')
    },
    
    closeMockModal() {
      this.mockModalVisible = false
    },
    
    async saveMockList() {
      try {
        await setStorage({'mockList': this.mockList})
      } catch (error) {
        console.error('保存Mock规则失败:', error)
        this.$message.error('保存Mock规则失败')
      }
    },
    
    formatJson() {
      try {
        const parsed = JSON.parse(this.currentMock.json)
        this.currentMock.json = JSON.stringify(parsed, null, 2)
        this.$message.success('JSON格式化成功')
      } catch (error) {
        this.$message.error('JSON格式错误')
      }
    },
    
    validateJson() {
      try {
        JSON.parse(this.currentMock.json)
        this.$message.success('JSON格式正确')
      } catch (error) {
        this.$message.error('JSON格式错误: ' + error.message)
      }
    },
    
    importMock() {
      this.$message.info('导入Mock规则功能开发中')
    },
    
    exportMock() {
      this.$message.info('导出Mock规则功能开发中')
    },
    
    createMockFromRequest(request) {
      this.currentMock = {
        url: request.url,
        method: request.method,
        status: 200,
        delay: 0,
        description: `从请求创建: ${request.url}`,
        headers: '',
        json: '',
        enabled: true
      }
      this.mockModalTitle = '从请求创建Mock规则'
      this.editingMockIndex = -1
      this.mockModalVisible = true
    }
  }
}
</script>

<style scoped>
.section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.section-header h2 {
  margin: 0;
  color: #333;
}

.section-actions {
  display: flex;
  gap: 10px;
}

.filter-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.mock-list-container .mock-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 10px;
}

.mock-info {
  flex: 1;
}

.mock-url {
  font-weight: bold;
  margin-bottom: 5px;
}

.mock-method {
  color: #666;
  font-size: 12px;
}

.mock-description {
  color: #999;
  font-size: 12px;
}

.mock-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.json-tools {
  margin-top: 10px;
}

.json-tools .el-button {
  margin-right: 10px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}
</style>